Using if Statements in Python
Course: Python Programming
Topic: Using if Statements
Course Link: Python Training at JustAcademy
Demo Link: Register for a Course Demo
1. Introduction to if Statements in Python
In Python, an if statement is a fundamental decision-making structure that allows a program to execute a block of code only when a specified condition is true. It helps programs make decisions based on user input, variable values, calculations, and other conditions.
Programs often need to perform different actions depending on a situation. For example, an application may check whether a user is old enough to register, whether a student has passed an examination, or whether an account has sufficient balance before allowing a withdrawal. The if statement makes these conditional operations possible.
Python evaluates the condition in an if statement as a Boolean value, either True or False. If the condition evaluates to True, the indented code block executes. If it evaluates to False, the block is skipped.
Example
age = 20
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.
In this example, the condition age >= 18 is true because the value of age is 20. Therefore, Python executes the print() statement.
2. Learning Objectives
After completing this topic, learners should be able to:
- Understand the purpose of the
if statement in Python.
- Write the correct syntax for conditional statements.
- Evaluate conditions using comparison operators.
- Understand how Boolean expressions control program execution.
- Use indentation to define conditional code blocks.
- Apply
if statements to real-world programming problems.
- Identify and resolve common errors in conditional statements.
- Combine conditions using logical operators.
3. Syntax of the if Statement
The if statement follows a simple syntax in Python.
if condition:
statement_1
statement_2
Explanation of the syntax:
if: A Python keyword that begins a conditional statement.
condition: An expression evaluated to determine whether the block should execute.
:: A colon that marks the beginning of the conditional code block.
statement_1 and statement_2: Instructions executed when the condition is true.
- Indentation: Spaces at the beginning of each line indicate which statements belong to the conditional block.
Example
temperature = 35
if temperature > 30:
print("It is a hot day.")
print("Stay hydrated.")
print("Program completed.")
Output:
It is a hot day.
Stay hydrated.
Program completed.
Both indented statements execute because the temperature is greater than 30. The final statement executes regardless of whether the condition is true because it is outside the if block.
4. How an if Statement Works
Python processes an if statement through a sequence of steps.
- The program evaluates the condition following the
if keyword.
- Python determines whether the condition is true or false.
- If the condition is true, the indented block executes.
- If the condition is false, the block is skipped.
- Execution continues with the next statement outside the block.
Example
balance = 5000
withdrawal = 2000
if balance >= withdrawal:
print("Withdrawal is allowed.")
print("Thank you for using our service.")
Output:
Withdrawal is allowed.
Thank you for using our service.
The condition is true because 5000 is greater than 2000. The program prints the withdrawal message and then continues to the next statement.
5. Understanding Conditions in Python
A condition is an expression that Python evaluates to determine whether a particular action should be performed. Conditions commonly use comparison operators, logical operators, variables, and values.
5.1 Conditions Using Comparison Operators
Comparison operators compare two values and return either True or False.
| Operator |
Meaning |
Example |
Result |
== |
Equal to |
5 == 5 |
True |
!= |
Not equal to |
5 != 3 |
True |
> |
Greater than |
8 > 4 |
True |
< |
Less than |
2 < 7 |
True |
>= |
Greater than or equal to |
10 >= 10 |
True |
<= |
Less than or equal to |
4 <= 6 |
True |
Example
marks = 85
if marks >= 40:
print("The student has passed.")
Output:
The student has passed.
The condition checks whether the marks are at least 40. Since the student has scored 85, the condition evaluates to true.
5.2 Conditions Using Variables
A condition can use the value stored in a variable. The variable's current value determines whether the block executes.
stock_quantity = 15
if stock_quantity > 0:
print("Product is available.")
Output:
Product is available.
If stock_quantity were zero or negative, the condition would be false and the message would not be printed.
6. Using Boolean Values with if Statements
Python provides two Boolean values: True and False. These values represent logical truth and falsity and can be used directly in conditional statements.
Example with True
is_logged_in = True
if is_logged_in:
print("Welcome back!")
Output:
Welcome back!
Example with False
is_logged_in = False
if is_logged_in:
print("Welcome back!")
Output:
The second program does not print anything because the condition is false.
7. Using Logical Operators in if Statements
Logical operators help combine or modify conditions. They are useful when a program must evaluate multiple requirements before executing a block of code.
| Operator |
Purpose |
Example |
and |
True when both conditions are true. |
age >= 18 and has_id |
or |
True when at least one condition is true. |
is_student or has_discount |
not |
Reverses a Boolean result. |
not is_blocked |
7.1 Using and
age = 22
has_license = True
if age >= 18 and has_license:
print("You can drive.")
Output:
You can drive.
Both conditions are true, so the message is displayed.
7.2 Using or
is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
print("You can relax today.")
Output:
You can relax today.
Only one condition needs to be true for the or expression to evaluate to true.
7.3 Using not
is_raining = False
if not is_raining:
print("You can go for a walk.")
Output:
You can go for a walk.
The not operator reverses the Boolean value of is_raining.
8. Understanding Indentation in if Statements
Indentation is essential in Python because it defines the beginning and end of a code block. Unlike some programming languages that use braces, Python typically uses four spaces to indent statements inside an if block.
Correct Indentation
number = 10
if number > 0:
print("Positive number")
print("Condition is true")
Incorrect Indentation
number = 10
if number > 0:
print("Positive number")
The incorrect example raises an IndentationError because the statement following the colon is not indented.
Best practices for indentation:
- Use four spaces for each indentation level.
- Keep statements belonging to the same block aligned.
- Avoid mixing tabs and spaces.
- Use your code editor's automatic indentation feature.
9. Using if Statements with User Input
The input() function allows a program to accept information from a user. The received value is a string by default. When comparing numeric input, convert it to the appropriate numeric type.
Example: Checking Age
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
Sample input:
Enter your age: 21
Output:
You are an adult.
The int() function converts the input string to an integer. If the user enters non-numeric text, the conversion raises a ValueError. Real applications should validate user input and handle invalid values appropriately.
Example: Checking a Minimum Purchase Amount
amount = float(input("Enter purchase amount: "))
if amount >= 1000:
print("You qualify for a special offer.")
This example uses float() because purchase amounts can include decimal values.
10. Using if Statements with Strings
Conditions can compare strings to check names, commands, categories, and other text values. String comparisons are case-sensitive by default.
Example
role = "admin"
if role == "admin":
print("Access granted.")
Output:
Access granted.
Case-Insensitive Comparison
user_choice = input("Enter yes or no: ")
if user_choice.strip().lower() == "yes":
print("You selected yes.")
The strip() method removes leading and trailing whitespace, while lower() converts the text to lowercase. This makes the comparison more flexible.
11. Using if Statements with Lists and Collections
Python allows conditions to check whether collections contain elements or whether a collection is empty. These checks are commonly used in data processing and application development.
11.1 Checking Membership
allowed_users = ["Amit", "Priya", "Neha"]
username = "Priya"
if username in allowed_users:
print("User is authorized.")
Output:
User is authorized.
11.2 Checking Whether a List Is Not Empty
cart = ["Laptop", "Mouse"]
if cart:
print("Your shopping cart contains items.")
Output:
Your shopping cart contains items.
An empty list evaluates to false in a Boolean context, whereas a non-empty list evaluates to true.
12. Truthy and Falsy Values
Python does not require every condition to be an explicit comparison. Many values can be evaluated directly in an if statement. Values that behave like true are called truthy, while values that behave like false are called falsy.
| Falsy Values |
Explanation |
False |
Boolean false. |
None |
Represents the absence of a value. |
0 and 0.0 |
Numeric zero values. |
"" |
An empty string. |
[] |
An empty list. |
{} |
An empty dictionary. |
() |
An empty tuple. |
set() |
An empty set. |
Example
username = ""
if username:
print("Username is provided.")
if not username:
print("Username is empty.")
Output:
Username is empty.
Because an empty string is falsy, the first block is skipped and the second block executes.
13. Difference Between if and if-else
An if statement executes a block only when its condition is true. An if-else statement provides an alternative block that executes when the condition is false.
| Feature |
if |
if-else |
| Purpose |
Executes code when a condition is true. |
Selects between two alternative blocks. |
| False condition |
The block is skipped. |
The else block executes. |
| Alternative block |
Not required. |
Provided using else. |
Example Using if
number = 8
if number > 0:
print("Positive number")
Example Using if-else
number = -8
if number > 0:
print("Positive number")
else:
print("Zero or negative number")
Output:
Zero or negative number
Use if when only one condition needs to trigger an action. Use if-else when the program must choose between two alternatives.
14. Nested if Statements
A nested if statement is an if statement placed inside another if statement. It is useful when one condition must be satisfied before another condition is evaluated.
Example
age = 25
has_ticket = True
if age >= 18:
if has_ticket:
print("You can enter the event.")
Output:
You can enter the event.
The inner condition is reached only when the outer condition is true. Both conditions must be true for the message to appear.
Nested if Best Practices
- Avoid unnecessary nesting because deeply nested code can be difficult to read.
- Use logical operators when they express the same requirement more clearly.
- Keep indentation consistent at every level.
- Use meaningful variable names that explain the conditions.
15. Practical Applications of if Statements
15.1 Checking Exam Results
marks = 76
if marks >= 40:
print("Result: Pass")
The program displays a pass message when marks are at least 40.
15.2 Checking Account Balance
balance = 2500
minimum_balance = 1000
if balance >= minimum_balance:
print("Minimum balance requirement satisfied.")
This condition can help demonstrate basic account validation. Actual financial applications require more extensive validation and security controls.
15.3 Checking Product Availability
quantity = 12
if quantity > 0:
print("Product is in stock.")
This example can be used in an inventory management application to check whether a product is available.
15.4 Checking Temperature
temperature = 38
if temperature > 35:
print("High temperature detected.")
The condition triggers the message when the temperature exceeds 35.
15.5 Checking Login Status
logged_in = True
if logged_in:
print("Welcome to your dashboard.")
This example demonstrates a basic login-state check. Real authentication must verify credentials and authorization securely rather than relying on a simple Boolean variable.
16. Common Errors When Using if Statements
16.1 Forgetting the Colon
Incorrect:
age = 20
if age >= 18
print("Eligible")
Problem: The colon is missing after the condition, resulting in a SyntaxError.
Correct:
age = 20
if age >= 18:
print("Eligible")
16.2 Incorrect Indentation
Incorrect:
if True:
print("Hello")
Problem: The statement is not indented inside the conditional block.
Correct:
if True:
print("Hello")
16.3 Using Assignment Instead of Comparison
Incorrect:
number = 10
if number = 10:
print("Number is ten")
Problem: A single equals sign assigns a value. It cannot be used as a comparison in an if condition.
Correct:
number = 10
if number == 10:
print("Number is ten")
16.4 Comparing Incompatible Data Types
Some comparisons between incompatible types raise a TypeError.
Example:
age = "20"
if age > 18:
print("Adult")
This comparison raises a TypeError in Python 3 because a string and an integer cannot be ordered this way.
Correct:
age = int("20")
if age > 18:
print("Adult")
16.5 Using the Wrong Comparison Operator
Using = instead of ==, or accidentally reversing a comparison, can cause syntax errors or incorrect results. Review the intended condition carefully.
16.6 Writing a Condition That Is Always True
Consider the following example:
age = 15
if age > 18 or age < 60:
print("Condition satisfied")
The condition is true for age 15 because age < 60 is true. If the intention is to check whether an age is between 18 and 59, use and instead of or.
Correct:
age = 25
if age >= 18 and age < 60:
print("Age is within the specified range.")
17. Best Practices for Writing if Statements
- Keep conditions readable: Avoid unnecessarily long expressions.
- Use meaningful variable names: Names such as
is_active and has_permission make conditions easier to understand.
- Use consistent indentation: Prefer four spaces per indentation level.
- Avoid redundant comparisons: Write
if is_active: instead of if is_active == True:.
- Validate user input: Convert values to suitable types and handle invalid input.
- Check boundary values: Test values immediately below, equal to, and above a threshold.
- Use parentheses when helpful: Parentheses can improve readability in complex expressions.
- Avoid excessive nesting: Simplify logic where possible.
- Test both outcomes: Confirm what happens when the condition is true and when it is false.
- Keep related logic together: Group statements that belong to the same decision.
18. Mini Project: Eligibility Checker
Project Objective: Create a simple program that checks whether a person meets a minimum age requirement for an activity.
Project Code
print("Activity Eligibility Checker")
try:
age = int(input("Enter your age: "))
if age < 0:
print("Age cannot be negative.")
if age >= 18:
print("You meet the minimum age requirement.")
except ValueError:
print("Please enter a valid whole number.")
Sample Output 1
Activity Eligibility Checker
Enter your age: 24
You meet the minimum age requirement.
Sample Output 2
Activity Eligibility Checker
Enter your age: 15
In the second example, the age is below 18, so the eligibility message is not displayed.
Sample Output 3
Activity Eligibility Checker
Enter your age: abc
Please enter a valid whole number.
Project Explanation
- The
input() function collects the age from the user.
- The
int() function converts the entered text to an integer.
- The first
if statement checks whether the age is negative.
- The second
if statement checks whether the age is at least 18.
- The
try-except block handles invalid integer input.
This project demonstrates how conditions can be combined with user input and exception handling to build a simple interactive program.
19. Practice Exercises
Complete the following exercises to strengthen your understanding of the if statement.
Exercise 1: Positive Number
Write a program that checks whether a number is greater than zero.
Exercise 2: Voting Eligibility
Ask the user to enter their age and display a message if they are at least 18 years old.
Exercise 3: Passing Marks
Store a student's marks in a variable. Display a pass message if the marks are at least 40.
Exercise 4: Discount Eligibility
Check whether a purchase amount is at least 2,000. Display a discount eligibility message if the condition is true.
Exercise 5: Even Number
Use the modulus operator to check whether a number is even.
Exercise 6: Password Length
Check whether a password contains at least eight characters. This exercise demonstrates length checking only, not complete password security validation.
Exercise 7: Product Availability
Create a list of product names and use an if statement to check whether a selected product exists in the list.
Exercise 8: Temperature Alert
Display a warning if a temperature value exceeds a specified threshold.
Exercise 9: Positive Balance
Write a program that displays a message when an account balance is greater than zero.
Exercise 10: Check an Empty String
Store a string in a variable and use an if statement to check whether it is empty.
20. Interview Questions and Answers
Q1. What is an if statement in Python?
An if statement is a decision-making statement that executes a block of code when a specified condition evaluates to true.
Q2. What is the purpose of a condition?
A condition determines whether a particular block of code should execute. It commonly evaluates to a Boolean value.
Q3. Why is a colon required after an if condition?
The colon marks the beginning of the conditional suite, which contains the statements controlled by the condition.
Q4. Why is indentation important in Python?
Indentation defines the structure of code blocks and indicates which statements belong to a particular conditional statement.
Q5. What happens when an if condition is false?
The statements inside the corresponding if block are skipped, and execution continues after the block.
Q6. Can an if statement contain multiple conditions?
Yes. Conditions can be combined using logical operators such as and and or, or modified using not.
Q7. What is a nested if statement?
A nested if statement is an if statement placed inside another conditional block.
Q8. What is the difference between = and ==?
A single equals sign, =, assigns a value to a variable. A double equals sign, ==, compares two values for equality.
Q9. Can strings be used in if conditions?
Yes. Strings can be compared with other strings, checked for membership, or evaluated for truthiness.
Q10. What are truthy and falsy values?
Truthy values behave like true in a Boolean context. Falsy values, including False, None, zero, and empty collections, behave like false.
Q11. What error occurs when the if block is not indented?
Python generally raises an IndentationError when a required block is not indented correctly.
Q12. Can an if statement work without an else statement?
Yes. An if statement can be used independently when an action is required only if the condition is true.
21. Quick Revision Notes
- The
if statement is used for conditional execution.
- The basic syntax is
if condition:.
- A colon must follow the condition.
- Statements in the conditional block must be indented.
- Comparison operators help evaluate conditions.
- Logical operators combine or modify conditions.
- Truthy and falsy values can be used directly in conditions.
- An
if statement without an else block skips its body when the condition is false.
- Nested conditions allow one decision to depend on another.
- User input often requires type conversion and validation.
- Readable conditions and consistent indentation improve code quality.
22. Conclusion
The if statement is one of the most important building blocks in Python programming. It enables programs to make decisions, evaluate conditions, and execute code selectively. By using comparison operators, logical operators, variables, user input, and collection checks, developers can create programs that respond intelligently to different situations.
Mastering the if statement provides a strong foundation for learning if-else statements, elif chains, loops, functions, input validation, and more advanced programming concepts. Regular practice with small exercises and real-world examples will help you write clear and reliable conditional logic.
Learn more: Explore Python Training at JustAcademy
Book a demo: Register for a JustAcademy Course Demo